package com.wss.common.adapter;

import com.wss.common.base.BaseFragment;
import com.wss.common.bean.HorizontalTabTitle;
import ohos.agp.components.*;
import java.util.List;

public class FragmentPagerAdapter extends PageSliderProvider {

    private List<HorizontalTabTitle> titles;
    private List<BaseFragment> fragments;

    public FragmentPagerAdapter(List<HorizontalTabTitle> titles) {
        this(titles, null);
    }

    public FragmentPagerAdapter(List<HorizontalTabTitle> titles, List<BaseFragment> fragments) {
        this.titles = titles;
        this.fragments = fragments;
    }

    @Override
    public int getCount() {
        return titles != null ? titles.size() : 0;
    }

    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int position) {
        BaseFragment fragment = null;
        if (fragments == null || fragments.isEmpty()) {
            fragment = getTabFragment();
        } else {
            fragment = fragments.get(position);
        }
        if (fragment == null) {
            throw new NullPointerException("Switch Fragment can not be empty!");
        }
        fragment.setTabTitle(titles.get(position));
        ComponentParent componentParent = fragment.getRootView().getComponentParent();
        if (componentParent == null) {
            componentContainer.addComponent(fragment.getRootView());
        }
        System.out.println("==== create page in container position : " + position + " , title : " + fragment.getTabTitle().getTitle() + " , data : " + fragment.getTabTitle().getData());
        return fragment;
    }

    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
        componentContainer.removeComponent(((BaseFragment)o).getRootView());
    }

    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        return true;
    }

    public String getPageTitle(int position) {
        return titles.get(position).getTitle();
    }

    /**
     * 使用两参构造方法 必须重写 该方法 返回对应的Fragment
     *
     * @return BaseFragment
     */
    public BaseFragment getTabFragment() {
        return null;
    }
}
